<template>
  <div class="pager-container">
    <a @click.prevent="handleClick(1)" :class="{ disabled: current === 1 }">|&lt;&lt;</a>
    <a @click.prevent="handleClick(current - 1)" :class="{ disabled: current === 1 }">&lt;&lt;</a>
    <a @click.prevent="handleClick(n)" v-for="(n, i) in numbers" :key="i" :class="{ active: n === current }">{{ n }}</a>
    <a @click.prevent="handleClick(current + 1)" :class="{ disabled: current === pageNumber }">&gt;&gt;</a>
    <a @click.prevent="handleClick(pageNumber)" :class="{ disabled: current === pageNumber }">&gt;&gt;|</a>
  </div>
</template>

<script>
export default {
  name: 'Pager',
  props: {
    current: {
      type: Number,
      default: 1,
    },
    total: {
      type: Number,
      default: 0,
    },
    limit: {
      type: Number,
      default: 10,
    },
    visibleNumber: {
      type: Number,
      default: 10,
    },
  },
  computed: {
    pageNumber() {
      return Math.ceil(this.total / this.limit)
    },
    visibleMin() {
      return Math.max(this.current - Math.floor(this.visibleNumber / 2), 1)
    },
    visibleMax() {
      return Math.min(this.visibleMin + this.visibleNumber - 1, this.pageNumber)
    },
    numbers() {
      let nums = []
      for (let i = this.visibleMin; i <= this.visibleMax; i++) {
        nums.push(i)
      }
      return nums
    },
  },
  methods: {
    handleClick(newPage) {
      if (newPage === this.current) return
      newPage = Math.min(Math.max(newPage, 1), this.pageNumber)
      this.$emit('pageChange', newPage)
    },
  },
}
</script>

<style scoped lang="less">
@import '~@/styles/var.less';
.pager-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
  a {
    color: @primary;
    margin: 0 6px;
    cursor: pointer;
    &.disabled {
      color: @lightWords;
      cursor: not-allowed;
    }
    &.active {
      color: @words;
      font-weight: bold;
      cursor: text;
    }
  }
}
</style>
